﻿using System;
using System.Configuration;
using System.Data.EntityClient;
using System.Data.SqlClient;
using Ninject;
using nanoCMS.Core.Concrete;
using nanoCMS.Core.Membership;
using nanoCMS.Core.Providers;

namespace nanoCMS.Core {
	public class WorldContext {
		private readonly string connectionStringName;
		private Entities entities;
		private UserProvider userProvider;
		private MessageProvider messageProvider;
		private TenantProvider tenantProvider;
		private ModuleProvider moduleProvider;
		private SqlConnection sqlConnection;

		[Inject]
		public WorldContext() {
			this.connectionStringName = "DataSource";
		}

		public string SqlConnectionString {
			get {
				return
					new SqlConnectionStringBuilder(
						ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString) {
							PersistSecurityInfo = true,
							MultipleActiveResultSets = true
						}.ConnectionString;
			}
		}

		public string EntityConnectionString {
			get {
				return new EntityConnectionStringBuilder() {
					Provider = "System.Data.SqlClient",
					Metadata = @"res://*/",
					ProviderConnectionString = SqlConnectionString
				}.ConnectionString;
			}
		}

		public SqlConnection SqlConnection
		{
			get { return sqlConnection ?? (sqlConnection = new SqlConnection(SqlConnectionString)); }
		}

		public CacheProvider CacheProvider {
			get { return CacheProvider.Default; }
		}

		internal Entities Entities {
			get { return entities ?? (entities = new Entities(EntityConnectionString)); }
		}

		public System.Web.HttpContext CurrentHttpContext {
			get { return System.Web.HttpContext.Current; }
		}

		
		public int CurrentUserID {
			get {
				if (SessionManagerBase.CurrentUser != null)
					return SessionManagerBase.CurrentUser.UserID;
				throw new Exception("There is no logged in user");
			}
		}

		public UserProvider UserProvider {
			get { return userProvider ?? (userProvider = new UserProvider(Entities, CurrentHttpContext)); }
		}

		public MessageProvider MessageProvider {
			get { return messageProvider ?? (messageProvider = new MessageProvider(Entities)); }
		}

		public TenantProvider TenantProvider {
			get { return tenantProvider ?? (tenantProvider = new TenantProvider(Entities)); }
		}

		public ModuleProvider ModuleProvider {
			get { return moduleProvider ?? (moduleProvider = new ModuleProvider(Entities)); }
		}

		public static int TenantID {
			get
			{
				if (System.Web.HttpContext.Current.Items.Contains("TenantID"))
			        return Convert.ToInt32(System.Web.HttpContext.Current.Items["TenantID"]);
				return -1;
			}
			set { System.Web.HttpContext.Current.Items.Add("TenantID", value); }
		} 

	}
}
